import { genChartUsingPOST } from '@/services/YuyuyuBI/ChartController';
import { Button, Card, Col, Divider, Form, message, Row, Select, Space, Spin, Upload } from 'antd';
import React, { useState } from 'react';

import { UploadOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { CHART_TYPE } from "@/constants";
import {
  ProFormCheckbox,
} from '@ant-design/pro-components';

const GenChart: React.FC = () => {
  const [option, setOption] = useState<any>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [isSkip, setIsSkip] = useState(false);

  const handleCheckboxChange = (event) => {
    const isSkipValue = event.target.checked;
    setIsSkip(isSkipValue);
  };

  /**
   * 提交表单
   * @param values
   */
  const onFinish = async (values: any) => {
    // 避免重复提交
    if (submitting) {
      return;
    }
    // 开始提交
    setSubmitting(true);
    setOption(undefined);

    const param = {
      ...values,
      isSkip: isSkip,
      file: undefined,
    };

    try {
      const res = await genChartUsingPOST(param, {}, values.file.file.originFileObj);
      if (!res?.data) {
        message.error('可视化失败');
      } else {
        message.success('可视化成功');
        const data = res.data;
        if (data.chartType === 'bar' || data.chartType === 'line'){
          // 柱状图，折线图
          const newOption = {
            xAxis: {
              name: data.xaxisName ? data.xaxisName : undefined,
              type: 'category',
              data: data.labels
            },
            yAxis: {
              name: data.yaxisName ? data.yaxisName : undefined,
              type: 'value'
            },
            series: [
              {
                type: data.chartType,
                data: data.values
              }
            ]
          };
          setOption(newOption);
        }else if (data.chartType === 'pie'){
          // 饼图
          const newOption = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: data.pieDataList.map((item: { name: any; }) => item.name)
            },
            series: [
              {
                name: data.xaxisName,
                type: 'pie',
                radius: '50%',
                data: data.pieDataList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };
          setOption(newOption);
        }
      }
    } catch (e: any) {
      message.error('可视化失败,' + e.message);
    }
    // 提交完成
    setSubmitting(false);
  };

  return (
    <div className="add-chart">
      <Row gutter={24}>
        <Col span={12}>
          <Card>
            <Divider style={{ fontWeight: 'bold', color: '#1677ff' }}>图表可视化</Divider>
            <Form
              name="addChart"
              labelAlign="left"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              onFinish={onFinish}
              initialValues={{ isSkip: false }}
            >
              <Form.Item
                name="isSkip"
                label="数据说明"
                tooltip="勾选此项表示首行是否为表头行，若勾选则表示存在表头行，反之则无。"
                valuePropName="checked"
                initialValue={false}
              >
                <ProFormCheckbox
                  noStyle
                  name="isSkip"
                  value={isSkip}
                  onChange={handleCheckboxChange}
                >
                  首行是否为表头行
                </ProFormCheckbox>
              </Form.Item>

              <Form.Item
                name="chartType"
                label="图表类型"
                rules={[{ required: true, message: '请选择图表类型！' }]}
              >
                <Select
                  options={CHART_TYPE}
                ></Select>
              </Form.Item>

              <Form.Item name="file" label="原始数据">
                <Upload name="file" maxCount={1} accept=".csv,.xls,.xlsx,.json,.txt,.xml,.sql">
                  <Button icon={<UploadOutlined />}>上传 Excel 文件</Button>
                </Upload>
              </Form.Item>

              <Form.Item wrapperCol={{ span: 16, offset: 4 }}>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={submitting}
                    disabled={submitting}
                  >
                    确定上传
                  </Button>
                  <Button htmlType="reset">重置内容</Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        <Col span={12}>
          <Card>
            <Divider style={{ fontWeight: 'bold', color: '#1677ff' }}>可视化图表</Divider>
            <Card>
              {option? (
                <ReactECharts option={option} />
              ) : (
                <div
                  style={{
                    color: '#FFA500',
                    textAlign: 'center',
                    fontWeight: 'bold',
                    fontSize: '16px',
                  }}
                >
                  请先提交数据 ^_^
                </div>
              )}
              <Spin spinning={submitting} size="large" />
            </Card>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default GenChart;
